package com.abocide.appium.sdk.core.xml;

import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class Page {
    /**
     * 根节点
     */
    private Node root;
    /**
     * 内容映射
     */
    private Map<String, List<Node>> contentMap;
    /**
     * 唯一键映射
     */
    private Map<String, Node> keyMap;
    /**
     * 深度映射
     */
    private Map<Integer, List<Node>> depthMaps;
    /**
     * 源内容
     */
    private String pageSource;


    public Page() {
        this.contentMap = new HashMap<>();
        this.keyMap = new HashMap<>();
        this.depthMaps = new HashMap<>();
    }

    public Node getRoot() {
        return this.root;
    }

    public void setRoot(Node root) {
        this.root = root;
    }

    public Map<String, List<Node>> getContentMap() {
        return contentMap;
    }

    public void setContentMap(Map<String, List<Node>> contentMap) {
        this.contentMap = contentMap;
    }

    public Map<String, Node> getKeyMap() {
        return keyMap;
    }

    public void setKeyMap(Map<String, Node> keyMap) {
        this.keyMap = keyMap;
    }

    public Map<Integer, List<Node>> getDepthMaps() {
        return depthMaps;
    }

    public void setDepthMaps(Map<Integer, List<Node>> depthMaps) {
        this.depthMaps = depthMaps;
    }

    public String getPageSource() {
        return pageSource;
    }

    public void setPageSource(String pageSource) {
        this.pageSource = pageSource;
    }

    /**
     * 根据唯一键获取元素
     *
     * @param key
     * @return
     */
    public Node getByKey(String key) {
        return this.keyMap.get(key);
    }

    /**
     * 根据深度获取节点
     *
     * @param depth
     * @return
     */
    public List<Node> getListByDepth(Integer depth) {
        return this.depthMaps.get(depth);
    }

    /**
     * 根据内容查询
     *
     * @param content
     * @return
     */
    public List<Node> getListByContent(String content) {
        return this.contentMap.get(content);
    }

    /**
     * 根据内容获取第一个元素
     */
    public Node getByContent(String content) {
        List<Node> listByContent = getListByContent(content);
        return CollectionUtils.isEmpty(listByContent) ? null : listByContent.get(0);
    }

    public List<Node> getListByLike(String content) {
        return this.keyMap.values()
                .stream()
                .filter(item -> item.getContentDesc().contains(content))
                .collect(Collectors.toList());
    }

    public List<Node> getNodeByClass(String className) {
        Map<String, Node> keyMap = this.getKeyMap();
        Collection<Node> values = keyMap.values();
        return values.stream().filter(item -> item.getClassName().equals(className)).collect(Collectors.toList());
    }


}
